package com.ishare.admin.controller;

import com.ishare.admin.service.SysUserService;
import com.ishare.admin.service.SysUserTokenService;
import com.ishare.common.base.BaseController;
import com.ishare.common.entity.bo.SysLoginBo;
import com.ishare.common.entity.po.SysUser;
import com.ishare.common.exception.BusinessException;
import com.ishare.common.wrapper.Wrapper;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.apache.shiro.crypto.hash.Sha256Hash;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;

/**
 * 登录相关
 * @author Mark sunlightcs@gmail.com
 */
@RestController
@Api(tags = {"系统登录-管理后台"})
public class SysLoginController extends BaseController {
    @Autowired
    private SysUserService sysUserService;

    @Autowired
    private SysUserTokenService sysUserTokenService;

    /**
     * 登录
     */
    @PostMapping("/login")
    @ApiOperation(value = "登录",notes = "后台用户登陆")
    public Wrapper login(@RequestBody SysLoginBo form) {

        //用户信息
        SysUser user = sysUserService.queryByAccount(form.getAccount());

        //账号不存在、密码错误
        if (user == null || !user.getPwd().equals(new Sha256Hash(form.getPassword(), user.getSalt()).toHex())) {
            throw new BusinessException("账号或密码不正确");
        }

        //账号锁定
        if (user.getEnable() == 0) {
            throw new BusinessException("账号已被锁定,请联系管理员");
        }

        //生成token，并保存到数据库
        return sysUserTokenService.createToken(user);
    }


    /**
     * 退出
     */
    @PostMapping("/logout")
    @ApiOperation(value = "退出登录",notes = "退出登录,同时清除Cookie")
    public Wrapper logout() {
        sysUserTokenService.logout(getUserId());
        return Wrapper.ok();
    }

}
